package com.linln.common.utils;


import org.apache.logging.log4j.util.Strings;
import org.springframework.util.Base64Utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 签名工具类
 *
 **/
public class SignUtil {

    /**
     * 获取签名信息
     * @param data
     * @param secret
     * @return
     */
    public static String getSign(Map<String, String> data, String secret) {
        // 由于map是无序的，这里主要是对key进行排序（字典序）
        Set<String> keySet = data.keySet();
        String[] keyArr = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArr);
        StringBuilder sbd = new StringBuilder();
        for (String k : keyArr) {
            if (Strings.isNotEmpty(data.get(k))) {
                sbd.append(k).append("=").append(data.get(k)).append("&");
            }
        }
        // secret最后拼接
        sbd.append("secret=").append(secret);
        return WxMD5Util.hash(sbd.toString());
    }

    public static void main(String[] args){
        Map<String, String> headers = new HashMap<>(4);
        String aa=String.valueOf(new Date().getTime());

        //appid=c13b6f87496ba6f5&timestamp=1601105314157&nonce=vlz3y0hv&secret=65477494c13b6f87496ba6f589c49d48
        headers.put("appid", "j41xJk6jV316EA6C");
        headers.put("timestamp", "1618295336748");
        headers.put("nonce", "v");
        String sign = SignUtil.getSign(headers,"80325192F0444f51B6b482c67e18329d");
        System.out.println(aa+"   |   "+sign);

        System.out.println(encodePassword("CdKzQ@2020_NCB"));
    }

    public static String encodePassword(String password) {
        String encodeStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            encodeStr = Base64Utils.encodeToString(md5.digest(password.getBytes("utf-8")));
        } catch (UnsupportedEncodingException var4) {
        } catch (NoSuchAlgorithmException var5) {
        }
        return encodeStr;
    }

}
